package com.hxkcloud.patient.activitys;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hxkcloud.patient.R;
import com.hxkcloud.patient.adapter.ScaleQuestionAdapter;
import com.hxkcloud.patient.beans.PatientIdBean;
import com.hxkcloud.patient.beans.ScaleBean;
import com.hxkcloud.patient.beans.ScaleInfoBean;
import com.hxkcloud.patient.beans.resultbeans.ObjectResultBean;
import com.hxkcloud.patient.popup.CalendarPopWindow;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.UrlAddress;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.BrightnessUtils;
import com.hxkcloud.patient.utils.StringUtil;
import com.hxkcloud.patient.utils.Utils;
import com.hxkcloud.patient.views.pulltorefreshlayout.PullToRefreshLayout;
import com.hxkcloud.patient.views.pulltorefreshlayout.PullableRecyclerView;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by ray_lei on 2016/7/11.
 * 量表
 */
public class ScaleQuestionActivity extends BaseActivity implements View.OnClickListener, ScaleQuestionAdapter.ResultSelectedListener, PullToRefreshLayout.OnRefreshListener {

    public static int questionKind = 0;//0量表流程 1调查问卷流程

    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;

    private PullToRefreshLayout refreshLayout;
    private PullableRecyclerView recycleView;

    private List<ScaleInfoBean> scaleInfoList;
    private ScaleQuestionAdapter adapter;

    private PopupWindow viewCommentPopup;
    private Button viewBtn;
    private Button commentPBtn;
    private Button cancelBtn;
    private View view_divider;
    private Button commentNBtn;

    private int pageIndex = 1;
    private int pageSize = 15;

    private boolean isLoadMore = false;// 是否加载更多

    private ObjectResultBean<ScaleBean> resultBean;

    private int totalCount = 0;

    private String patientId;

    private ScaleInfoBean functionList;//popup展示时的order

    private String isFromAssistant = "";

    private CalendarPopWindow calendarView;
    private boolean isDoctorTest = false;//护士测评
    private boolean isUserTest = false;//用户自评

    private String createTime = "";

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_GETSCALELIST_SUCCESS:
                dismisssLoading();
                if (msg.obj != null) {
                    resultBean = (ObjectResultBean<ScaleBean>) msg.obj;
                    totalCount = Integer.parseInt(resultBean.getData().getTotalCount());
                    if (resultBean.getData().getList().size() == 0) {
                        if (isLoadMore) {
                            refreshLayout
                                    .loadmoreFinish(PullToRefreshLayout.SUCCEED);
                        } else {
                            scaleInfoList.clear();
                            adapter.setData(scaleInfoList);
                            refreshLayout
                                    .refreshFinish(PullToRefreshLayout.SUCCEED);
                        }
                    } else {
                        if (isLoadMore) {

                        } else {
                            scaleInfoList.clear();
                        }
                        scaleInfoList.addAll(resultBean.getData().getList());
                        adapter.setData(scaleInfoList);
                        if (isLoadMore) {
                            refreshLayout
                                    .loadmoreFinish(PullToRefreshLayout.SUCCEED);
                        } else {
                            refreshLayout
                                    .refreshFinish(PullToRefreshLayout.SUCCEED);
                        }

                    }

                }

                break;
            case MessageCode.NETWORKCODE_GETSCALELIST_FAILURE:
                dismisssLoading();
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                }

                break;
            case MessageCode.NETWORKCODE_SCALELISTUSE_SUCCESS:
                StringUtil.zhugeTrack(mContext, "提醒-量表-用户自评-完成按钮", "用户自评发送数");

                if (msg.obj != null) {
                    toastMsg(R.string.send_already);
                } else {
                    toastMsg(R.string.functionsuccess);
                }
//                finish();
                break;
            case MessageCode.NETWORKCODE_SCALELISTUSE_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.functionfail);
                }
                break;
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout_scalequestion);
        scaleInfoList = new ArrayList<ScaleInfoBean>();
        patientId = this.getIntent().getStringExtra("patientId");
        if (getIntent().hasExtra("isFromAssistant")) {
            isFromAssistant = getIntent().getStringExtra("isFromAssistant");
        }
        initView();
        initData();
        initListener();

        questionKind = 0;
    }

    @Override
    protected void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);

        tv_title.setText(getResources().getText(R.string.assistant_text_scale));


        refreshLayout = (PullToRefreshLayout) findViewById(R.id.scalequestion_refreshlayout);
        recycleView = (PullableRecyclerView) findViewById(R.id.scalequestion_recyclerview);

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(mLayoutManager);
        adapter = new ScaleQuestionAdapter(this, scaleInfoList, recycleView, this);
        recycleView.setAdapter(adapter);

        initPopup();

        if (calendarView == null) {
            calendarView = new CalendarPopWindow(this);
        }
        calendarView.setCalendarListener(new CalendarPopWindow.CalendarListener() {
            @Override
            public void setCalendar(String calendar) {
                createTime = Utils.date2TimeStamp(calendar, "yyyy-MM-dd");
                long createTimeL = Long.valueOf(createTime);
                Calendar calendar1 = Calendar.getInstance();
                long nowTime = calendar1.getTime().getTime();
                if (createTimeL > nowTime) {
                    toastMsg(R.string.selectdatecantlaterthannow);
                    return;
                }
                if (isDoctorTest) {
                    isDoctorTest = false;
                    Intent intent1 = new Intent(ScaleQuestionActivity.this, QuestionAssessActivity.class);
                    intent1.putExtra("url", UrlAddress.H5_QUESTIONASSESS_URL + "&isEdit=0" + "&patientId=" + patientId + "&createTime=" + createTimeL);
                    intent1.putExtra("title", mContext.getResources().getString(R.string.assessment));
                    intent1.putExtra("questionId", functionList.getScaleId());
                    intent1.putExtra("patientId", patientId);
                    intent1.putExtra("finishnext", true);
                    startActivityForResult(intent1, 100);
                }
                if (isUserTest) {
                    isUserTest = false;
                    if (functionList != null) {
                        if (!TextUtils.isEmpty(patientId)) {
                            List<PatientIdBean> patients = new ArrayList<>();
                            PatientIdBean pidb = new PatientIdBean();
                            pidb.setPatientId(patientId);
                            patients.add(pidb);
                            loading();
                            YiJiaHuNetWorkUtils.scaleListUse(patients, functionList.getScaleId(), createTime, handler);
                        } else {
                            Intent iPatient = new Intent(mContext, ChooseUserActivity.class);
                            startActivityForResult(iPatient, 123);
                        }
                    }
                }

            }
        });
        calendarView.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                isDoctorTest = false;
                isUserTest = false;
                BrightnessUtils.lightOn(ScaleQuestionActivity.this);
            }
        });


    }

    @Override
    protected void initListener() {
        iv_back.setOnClickListener(this);
        refreshLayout.setOnRefreshListener(this);
    }

    @Override
    protected void initData() {
        loading();
        YiJiaHuNetWorkUtils.getScaleList(loginInfo.getUserId(), pageIndex, pageSize, handler);


    }

    private void initPopup() {
        viewCommentPopup = new PopupWindow(this);
        View viewPopup = LayoutInflater.from(this).inflate(R.layout.popup_view_comment_select, null);
        viewCommentPopup.setContentView(viewPopup);

        viewCommentPopup.setWidth(screenWidth);
        viewCommentPopup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        viewCommentPopup.setFocusable(true);
        viewCommentPopup.setTouchable(true);
        viewCommentPopup.setOutsideTouchable(true);
        viewCommentPopup.setBackgroundDrawable(new ColorDrawable(0x00000000));
        viewCommentPopup.setAnimationStyle(R.style.popupwindow_anim_default);

        viewBtn = (Button) viewPopup.findViewById(R.id.select_btn_view);
        commentPBtn = (Button) viewPopup.findViewById(R.id.select_btn_commentp);
        cancelBtn = (Button) viewPopup.findViewById(R.id.select_btn_cancel);
        view_divider = viewPopup.findViewById(R.id.view_select_btn_comment);
        commentNBtn = (Button) viewPopup.findViewById(R.id.select_btn_commentn);

        viewBtn.setOnClickListener(this);
        commentPBtn.setOnClickListener(this);
        commentNBtn.setOnClickListener(this);
        cancelBtn.setOnClickListener(this);

        if (TextUtils.isEmpty(patientId)) {
            view_divider.setVisibility(View.GONE);
            commentNBtn.setVisibility(View.GONE);
        }

        viewCommentPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(ScaleQuestionActivity.this);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.select_btn_view:

                viewCommentPopup.dismiss();
                Intent intent = new Intent(ScaleQuestionActivity.this, QuestionAssessActivity.class);
                intent.putExtra("url", UrlAddress.H5_QUESTIONASSESS_URL + "&isEdit=1");
                intent.putExtra("title", mContext.getResources().getString(R.string.preview));
                intent.putExtra("questionId", functionList.getScaleId());
                intent.putExtra("patientId", patientId);
                intent.putExtra("isFromView", "true");
                intent.putExtra("isFromAssistant", isFromAssistant);
                intent.putExtra("answerType", functionList.getAnswerType());
                intent.putExtra("isScale", true);
                intent.putExtra("finishnext", true);
                startActivityForResult(intent, 100);

                break;
            case R.id.select_btn_commentp:
                if (functionList != null && functionList.getAnswerType().equals("1")) {
                    toastMsg(R.string.onlynurseassess);
                    return;
                }
                viewCommentPopup.dismiss();
                isUserTest = true;
//                calendarView.clearOldSelections();
//                calendarView.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
//                BrightnessUtils.lightOff(this);
                calendarView.showBottom(ll_title);

                break;
            case R.id.select_btn_commentn:
                if (functionList != null && functionList.getAnswerType().equals("2")) {
                    toastMsg(R.string.onlypatientassess);
                    return;
                }
                viewCommentPopup.dismiss();
                isDoctorTest = true;
//                calendarView.clearOldSelections();
//                calendarView.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
//                BrightnessUtils.lightOff(this);
                calendarView.showBottom(ll_title);

                break;
            case R.id.select_btn_cancel:
                viewCommentPopup.dismiss();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 123) {
            if (data != null) {

                List<String> ps = data.getStringArrayListExtra("patients");
                List<PatientIdBean> patients = new ArrayList<>();
                for (String p : ps) {
                    PatientIdBean pb = new PatientIdBean();
                    pb.setPatientId(p);
                    patients.add(pb);
                }
                loading();
                YiJiaHuNetWorkUtils.scaleListUse(patients, functionList.getScaleId(), createTime, handler);

            }
        }
        if (resultCode == RESULT_OK) {
            if (requestCode == 100) {
                if (data.getBooleanExtra("back", false)) {
                    Intent iBack = new Intent();
                    iBack.putExtra("back", true);
                    setResult(RESULT_OK, iBack);
                    finish();
                }
            }
        }
    }

    @Override
    public void onSelected(String type, ScaleInfoBean info) {

        if ("item".equals(type)) {
            functionList = info;
            viewCommentPopup.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
            BrightnessUtils.lightOff(ScaleQuestionActivity.this);

        }
    }

    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        isLoadMore = false;
        pageIndex = 1;
        scaleInfoList.clear();
        YiJiaHuNetWorkUtils.getScaleList(loginInfo.getUserId(), pageIndex, pageSize, handler);
    }

    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {

        if (scaleInfoList.size() == totalCount) {
            isLoadMore = false;
            refreshLayout
                    .loadmoreFinish(PullToRefreshLayout.SUCCEED);
            return;
        }

        isLoadMore = true;
        pageIndex++;
        YiJiaHuNetWorkUtils.getScaleList(loginInfo.getUserId(), pageIndex, pageSize, handler);

    }
}
